###################################################################################

library(data.table)
library(optparse)
library(dplyr)
library(ggplot2)
library(ggsci)
library(RColorBrewer)
library(ggpubr)
library(patchwork)

###################################################################################

option_list <- list(
    make_option(c("--input_file"), type = "character") ,
    make_option(c("--ccf_file"), type = "character") ,
    make_option(c("--ccf_msi_file"), type = "character") ,
    make_option(c("--class_sub_file"), type = "character") ,
    make_option(c("--mutshare_file"), type = "character") ,
    make_option(c("--mutshare_msi_file"), type = "character") ,
    make_option(c("--ddrPathway_file"), type = "character") ,
    make_option(c("--images_path"), type = "character")
)

if(1!=1){
    
    input_file <- "~/20220915_gastric_multiple/dna_combinePublic/baseTable/STAD_Info.addBurden.MSI_MSS.addCNVType.tsv"
    mutshare_file <- "~/20220915_gastric_multiple/dna_combinePublic/images/mutRate/MutShare.AllPoint.tsv"
    mutshare_msi_file <- "~/20220915_gastric_multiple/dna_combinePublic/images/mutRateMSI/MutShare.AllPoint.tsv"
    ccf_file <- "~/20220915_gastric_multiple/dna_combinePublic/mutationTime/result/All_CCF_mutTime.tsv"
    ccf_msi_file <- "~/20220915_gastric_multiple/dna_combinePublic/mutationTime/result/All_CCF_mutTime.MSI.tsv"
    images_path <-"~/20220915_gastric_multiple/dna_combinePublic/images/mutBurden"
    class_sub_file <- paste("~/20220915_gastric_multiple/dna_combinePublic/config/Class_order_sub.list",sep="")
    ddrPathway_file <- "~/ref/Pathway/DDR.list"

}

###########################################################################################

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

input_file <- opt$input_file
mutshare_msi_file <- opt$mutshare_msi_file
mutshare_file <- opt$mutshare_file
images_path <- opt$images_path
ccf_msi_file <- opt$ccf_msi_file
ccf_file <- opt$ccf_file
ddrPathway_file <- opt$ddrPathway_file
class_sub_file <- opt$class_sub_file

dir.create(images_path , recursive = T)

##############################################################################

col <- c(
  brewer.pal(9,"YlGnBu")[6],
  rgb(234,106,79,alpha=255,maxColorValue=255),
  rgb(203,24,30,alpha=255,maxColorValue=255),
  rgb(255,0,0,alpha=255,maxColorValue=255)
  )

names(col) <- c("IM" , "IGC" , "DGC" , "GC")

##############################################################################

info <- data.frame(fread(input_file))
dat_share <- data.frame(fread(mutshare_file))
dat_share_msi <- data.frame(fread(mutshare_msi_file))
dat_ccf <- data.frame(fread(ccf_file))
dat_ccf_msi <- data.frame(fread(ccf_msi_file))
ddr_gene <- data.frame(fread(ddrPathway_file , header = F))$V1
class_sub <- data.frame(fread(class_sub_file))

dat_ccf_use <- rbind( dat_ccf , dat_ccf_msi )
dat_share_use <- rbind( dat_share , dat_share_msi )

##############################################################################
## https://ascopubs.org/doi/full/10.1200/PO.17.00073
msi_gene <- c("MSH2" , "MSH6" , "MLH1" , "PMS2" , "EXO1" , "POLD1" , "POLE")
pol_gene <- unique(grep( "^POL" , dat_share_use$Hugo_Symbol , value = T))

use_gene <- unique(c(msi_gene , pol_gene , ddr_gene))

##############################################################################
## 提取MSI基因相关信息
dat_msi <- c() 
for( sample in unique(dat_share_msi$Tumor) ){

    tmp <- subset( dat_share_use , Tumor == sample )
    tmp_ccf <- subset( dat_ccf_use , Sample == sample )

    tmp$vid <- paste( tmp$Chromosome , tmp$Start_Position , tmp$End_Position , sep = ":" )
    tmp_ccf$vid <- paste( tmp_ccf$Chr , tmp_ccf$Start_Position , tmp_ccf$End_Position , sep = ":" )

    tmp_use <- merge( tmp , tmp_ccf[,c("vid" , "VAF" , "CCF_adj" , "CLS")] , by = "vid" )
    tmp_use <- subset( tmp_use , Hugo_Symbol %in% use_gene )        
    dat_msi <- rbind( dat_msi , tmp_use )
}

##############################################################################

dat <- merge( info , dat_msi , by = "Tumor" )
## 提取share突变
dat_ccf_use <- subset( dat , Share == "TRUE" )
dat_ccf_use$Class_sub.x <- factor( dat_ccf_use$Class_sub.x , levels = class_sub$Class , order = T )

##############################################################################

plotCCF <- function(dat_ccf_use = dat_ccf_use , out_name = out_name){

    plot <- ggplot(dat_ccf_use , mapping = aes(Class_sub.x , CCF_adj , fill = Class.x))+
        geom_bar(position = "stack", stat = "identity") + 
        facet_grid(vars(Hugo_Symbol) , vars(Patient) , scales = "free", space = "free") +
        scale_fill_manual(values=col) +
        xlab(NULL) +
        ylim(0,1) +
        ylab("Cell Fraction")+
        #geom_text(mapping = aes(x = Class_sub , y = 1.2 , label = CLS) , size=3 , face='bold' , color="black") +
        theme_bw() +
        theme(panel.background = element_blank(),#设置背影为白色#清除网格线
            legend.position ='none',
            legend.title = element_blank() ,
            panel.grid.major=element_line(colour=NA),
            plot.title = element_text(size = 8,color="black",face='bold'),
            legend.text = element_text(size = 10,color="black",face='bold'),
            axis.text.y = element_text(size = 5,color="black",face='bold'),
            axis.title.x = element_text(size = 10,color="black",face='bold'),
            axis.title.y = element_text(size = 10,color="black",face='bold'),
            axis.ticks.x = element_blank(),
            axis.text.x = element_text(size = 8,color="black",face='bold') ,
            strip.text.x = element_text(size = 10,color="black",face='bold') ,
            strip.text.y = element_text(size = 10,color="black",face='bold')
        ) 

    ## x轴每个柱子一样宽
    p <- plot
    gp <- ggplotGrob(p)
    facet.columns <- gp$layout$l[grepl("panel", gp$layout$name)]
    x.var <- sapply(ggplot_build(p)$layout$panel_scales_x,
                    function(l) length(l$range$range))
    gp$widths[facet.columns] <- gp$widths[facet.columns] * x.var
    
    if(type == "IM + IGC"){
         pdf(out_name , width=8 ,height=9)
    }else{
         pdf(out_name , width=5 ,height=6)
    }
   
    grid::grid.draw(gp)
    dev.off()

}

for(type in unique(dat_ccf_use$Type.x)){
    out_name <- paste0( images_path , "/mutCCF.MSIGene.bar.share." , gsub( " " , "" , type ) , ".pdf" ) 
    plotCCF(dat_ccf_use = subset( dat_ccf_use , Type.x == type ) , out_name = out_name)
}

